<template>
  <div>
    <el-card>
      <el-form
        label-width="100px"
        :model="skuInfo"
        ref="skuFormRef"
        :rules="skuRules"
      >
        <el-form-item label="SPU名称"
          ><span>{{ props.currentSpuInfo.spuName }}</span></el-form-item
        >
        <el-form-item label="SKU名称" prop="skuName">
          <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number
            v-model.number="skuInfo.price"
            class="mx-4"
            :min="1"
            :max="10"
            text-align="left"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="重量(千克)" prop="weight">
          <el-input-number
            v-model.number="skuInfo.weight"
            class="mx-4"
            :min="1"
            :max="10"
            align="left"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="规格描述" prop="skuDesc">
          <el-input
            v-model="skuInfo.skuDesc"
            type="textarea"
            placeholder="规格描述"
            row="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="skuAttrValueList">
          <el-row :gutter="10">
            <el-col
              style="margin-bottom: 10px"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="8"
              v-for="(attr, index) in attrList"
              :key="attr.id"
            >
              <el-form-item :label="attr.attrName">
                <el-select
                  placeholder="请选择"
                  v-model="skuInfo.skuAttrValueList[index]"
                  @change="clearAttrRules"
                >
                  <el-option
                    :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                    :label="attrValue.valueName"
                    v-for="attrValue in attr.attrValueList"
                    :key="attrValue.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <!-- v-model="skuInfo.skuSaleAttrValueList" -->
        <el-form-item label="销售属性" prop="skuSaleAttrValueList">
          <el-form-item
            :label="spuSaleAttr.saleAttrName"
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
          >
            <el-select
              placeholder="请选择"
              v-model="skuInfo.skuSaleAttrValueList[index]"
              @change="clearSaleAttrRules"
            >
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                v-for="saleAttrValue in spuSaleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item
          label="图片列表"
          prop="skuImageList"
          style="margin-bottom: 10px"
        >
          <el-table
            border
            ref="multipleTableRef"
            :data="spuImageList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="图片" align="center" width="300">
              <template v-slot="{ row }">
                <el-image
                  :src="row.imgUrl"
                  :alt="row.imgName"
                  style="width: 150px"
                />
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="imgName"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  v-if="row.isDefault === '0'"
                  @click="setDefault(row)"
                  >设置默认</el-button
                >
                <el-button type="success" v-else disabled>默认值</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(skuFormRef)"
            >保存</el-button
          >
          <el-button @click="emits('changeScene', 1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "SkuForm",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { reqGetSpuSaleAttrList, reqGetSpuImageList } from "@/api/product/spu"; //销售属性，图片属性
import { reqGetAttrValueList } from "@/api/product/attrList"; //平台属性
import { reqPostSaveSpuInfo } from "@/api/product/sku";
import { useCategoryListStore } from "@/stores/categoryList";
const categoryStore = useCategoryListStore();

// 定义变量，接收响应过来的数据
const attrList = ref([]);
const spuSaleAttrList = ref([]);
const spuImageList = ref([]);
const emits = defineEmits(["changeScene"]);
const props = defineProps(["currentSpuInfo"]);

// 1.挂载后就发送请求获取sku列表，销售属性，图片属性，平台属性
onMounted(async () => {
  const id = props.currentSpuInfo.id;
  console.log("id", id);

  const [resAttrList, resSpuImageList, resSpuSaleAttrList] =
    await Promise.allSettled([
      reqGetAttrValueList({
        category1Id: categoryStore.category1Id as number,
        category2Id: categoryStore.category2Id as number,
        category3Id: categoryStore.category3Id as number,
      }),
      reqGetSpuImageList(id),
      reqGetSpuSaleAttrList(id),
    ]);
  console.log(resAttrList, resSpuImageList, resSpuSaleAttrList);
  // 请求成功后赋值
  if (resAttrList.status === "fulfilled") attrList.value = resAttrList.value;
  if (resSpuImageList.status === "fulfilled") {
    spuImageList.value = resSpuImageList.value.map((item) => {
      return {
        ...item,
        isDefault: "0",
      };
    });
  }
  if (resSpuSaleAttrList.status === "fulfilled")
    spuSaleAttrList.value = resSpuSaleAttrList.value;
});

// 2.修改默认值 且获取默认图片地址 清除校验规则
const setDefault = (row) => {
  spuImageList.value.forEach((item) => (item.isDefault = "0"));
  row.isDefault = "1";
  // 保存一下默认图片的地址
  skuInfo.skuDefaultImg = row.imgUrl;
  // 在这里清空校验规则 这里可不写，因为之前的校验规则不需要清除
  const imgArr = skuInfo.skuImageList
  if(imgArr.length >= 3 && imgArr.some(item=>item.isDefault === '1')){
    skuFormRef.value?.clearValidate(['skuImageList'])
  }
};

// 收集添加Sku时的参数,用于保存时发送请求
const skuInfo = reactive({
  // spu名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: "",
  // 默认图片
  skuDefaultImg: "",
  // 平台属性 要组成一个数组，渲染时要合并，
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
});

//3. 获取图片地址
const handleSelectionChange = (url) => {
  skuInfo.skuImageList = url;
};

// 4.校验
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
const skuFormRef = ref<FormInstance>();
// 自定义校验图片，属性，销售属性
const validateSkuImageList = (rule: any, value: any, callback: any) => {
  // console.log(rule.value,callback);
  if (value.length < 3) return callback(new Error("请选择至少三张图片"));
  // 下面的判断是选择的三张图片中是否有默认项
  const flag = value.some((item) => item.isDefault === "1");
  if (!flag)
    return callback(new Error("选择的图片中不包含默认项,请添加默认项"));
  callback(); //这样写就不用清空校验了
};

const validateSkuAttrValueList = (rule: any, value: any, callback: any) => {
  if (value.length < 3) return callback(new Error("请选择至少三项属性"));
  callback();
};
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入Sku名称", trigger: "blur" },
    { min: 2, max: 10, message: "Sku名称在2---10之间", trigger: "blur" },
  ],
  price: [
    {
      type: "number",
      required: true,
      message: "请输入价格",
      trigger: "change",
    },
  ],
  weight: [
    {
      type: "number",
      required: true,
      message: "请输入重量",
      trigger: "change",
    },
  ],
  skuDesc: [
    { required: true, message: "请输入Sku描述", trigger: "blur" },
    { min: 2, max: 10, message: "Sku描述在2---10之间", trigger: "blur" },
  ],
  skuImageList: [
    {
      type: "array",
      required: true,
      validator: validateSkuImageList,
      trigger: "change",
    },
  ],
  skuAttrValueList: [
    {
      type: "array",
      required: true,
      validator: validateSkuAttrValueList,
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    {
      type: "array",
      required: true,
      message: "请至少选择一项销售属性",
      trigger: "change",
    },
  ],
});

// 提交表单验证 这里提交skuInfo，发送请求，不过要修正属性，销售属性因为服务器要求发送的是数组，所以要拼接，（）赋值skuId，3id
const formatData = () => {
  skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
    .filter(Boolean)
    .map((item: string) => {
      const [attrId, attrName, valueId, valueName] = item.split(":");
      return {
        attrId,
        attrName,
        valueId,
        valueName,
      };
    });

  skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
    .filter(Boolean)
    .map((item: string) => {
      const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
        item.split(":");
      return { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName };
    });
  skuInfo.spuId = props.currentSpuInfo.id;
  skuInfo.category3Id = props.currentSpuInfo.category3Id;
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      // 发送请求保存
      formatData();
      const result = await reqPostSaveSpuInfo(skuInfo);
      ElMessage.success("添加sku数据成功...");
      emits("changeScene", 1); // 跳转到skuList列表页
      console.log(result);

      console.log("submit!");
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// 符合规则后清空属性校验
const clearAttrRules = () => {
  const length = skuInfo.skuAttrValueList.filter(Boolean).length;
  if (length >= 3) skuFormRef.value?.clearValidate(["skuAttrValueList"]);
};

// 符合规则后清空销售属性校验
const clearSaleAttrRules = () => {
  skuFormRef.value?.clearValidate(["skuSaleAttrValueList"]);
};

</script>
<style>
</style>